<template>
	<el-tooltip :disabled="useTooltip" :content="content" placement="top">
		<template v-slot:content>
			<slot />
		</template>

		<div ref="refText" class="cy-overflow-label" v-bind="$attrs" @mouseenter="handleMouseEnter"
			@mouseleave="handleMouseLeave">
			<slot />
		</div>
	</el-tooltip>
</template>

<script setup name="cy-overflow">
import { ref } from 'vue'

defineProps({
	content: String
})

const refText = ref()
const visible = ref(false)
const useTooltip = ref(false)

const handleMouseEnter = () => {
	const range = document.createRange()
	const textDom = refText.value

	range.setStart(textDom, 0)
	range.setEnd(textDom, textDom.childNodes.length)

	const { width: rangeWidth } = range.getBoundingClientRect()
	const { width: textDomWidth } = textDom.getBoundingClientRect()
	useTooltip.value = rangeWidth <= textDomWidth
}

const handleMouseLeave = () => {
	visible.value = false
}
</script>

<style lang="scss">
.cy-overflow-label {
	width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
</style>
